package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryService categoryService;


    /*****
     * 菜品新增
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        boolean flag = dishService.saveWithDishFlaver(dishDto);
        return flag ? R.success("菜品添加成功!") : R.success("菜品添加失败!");
    }


    /******
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> pageSelect(int page, int pageSize, String name) {
        //1.分页构造
        Page<Dish> p = new Page<>(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>();
        //2.条件构造
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishService.page(p, lqw);

        //3.对象拷贝   (除了records,其他都拷贝)
        BeanUtils.copyProperties(p, dishDtoPage, "records");

        List<Dish> records = p.getRecords();
        List<DishDto> list = new ArrayList<>();

        for (Dish dish : records) {
            //1.创建一个对象进行拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            log.info("拷贝后的属性:{}",dishDto.toString());
            //2.给dishDto设置name属性
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            list.add(dishDto);
        }
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /*****
     * 修改菜品回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDish(@PathVariable long id){
        Dish dish = dishService.getById(id);
        DishDto dishDto = new DishDto();
        //拷贝
        BeanUtils.copyProperties(dish,dishDto);
        //查询口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(lqw);
        dishDto.setFlavors(list);
        //查询分类名称
        Category category = categoryService.getById(dish.getCategoryId());
        dishDto.setCategoryName(category.getName());
        return R.success(dishDto);
    }

    /*****
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        boolean flag = dishService.updateWithDishFlavar(dishDto);
        return flag ? R.success("修改菜品成功!") : R.success("修改菜品失败!");
    }


    /******
     * 菜品停售启售
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> tingShou(@RequestParam List<Long> ids,@PathVariable int status){
        //1.在禁用之前判断是否在套餐里里售卖,并且这个套餐在售状态
        if(status == 0){
            LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
            lqw.in(SetmealDish::getDishId,ids);
            List<SetmealDish> list = setmealDishService.list(lqw);
            for (SetmealDish setmealDish : list) {
                Long setmealId = setmealDish.getSetmealId();
                //根据setmealId去查询套餐状态
                Setmeal setmeal = setmealService.getById(setmealId);
                if(setmeal.getStatus() == 1){
                    throw new BusinessException("套餐中有该菜品在售,修改套餐后再来尝试");
                }
            }
        }


        //2.更改菜品状态菜品
        LambdaUpdateWrapper<Dish> dishlqw = new LambdaUpdateWrapper<>();
        dishlqw.in(Dish::getId,ids).set(Dish::getStatus,status);
        dishService.update(dishlqw);
        return R.success("菜品状态修改成功!");
    }


    /****
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.delete(ids);
        return R.success("菜品删除成功");
    }

    /****
     * 套餐管理查询菜品列表
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> getDishes(Dish dish){
        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //查询菜品,设置条件
        lqw.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(dish.getStatus() != null,Dish::getStatus,dish.getStatus());
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName,dish.getName());

        List<Dish> dishList = dishService.list(lqw);

        //查询菜品对应的口味
         dishDtoList = dishList.stream().map(item -> {
            //创建dishDto
            DishDto dishDto = new DishDto();
            //拷贝
            BeanUtils.copyProperties(item, dishDto);
            //查询菜品对应的口味
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(item.getId() != null, DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
         redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


}
